package com.jinzhi.jzweb.controller;


import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

import cn.afterturn.easypoi.entity.vo.MapExcelConstants;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.view.EasypoiMapExcelView;
import cn.afterturn.easypoi.view.PoiBaseView;
import com.jinzhi.common.utils.ApiResult;
import com.jinzhi.common.utils.JSONUtils;
import com.jinzhi.jzapi.utils.HttpClientUtil;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.pojo.ExaminationResultsExportVo;
import com.jinzhi.jzweb.service.InfoModelService;
import com.jinzhi.jzweb.service.InfoStoreService;
import com.jinzhi.jzweb.service.MsgService;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.jzweb.utils.EfficacyUtil;
import com.jinzhi.oss.service.FileService;
import com.jinzhi.sys.service.UserService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.jzweb.service.InfoCollectService;
import com.jinzhi.common.utils.Result;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * <pre>
 * 
 * </pre>
 * <small> 2021-02-23 15:32:23 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/infoCollect")
public class InfoCollectController extends BaseController {
	@Autowired
	private InfoStoreService infoStoreService;
	@Autowired
	private InfoCollectService infoCollectService;
	@Autowired
	private InfoModelService infoModelService;
	@Autowired
	private UserService userService;
	@Autowired
	private MsgService msgService;

	@GetMapping()
	@RequiresPermissions("jzweb:infoCollect:infoCollect")
	String InfoCollect(Long id,Model model){
		model.addAttribute("infoStoreId",id);
		return "jzweb/infoCollect/infoCollect";
	}

	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:infoCollect:infoCollect")
	public Result<Page<InfoCollectDO>> list(InfoCollectDO infoCollectDTO){
		Wrapper<InfoCollectDO> wrapper = new EntityWrapper<InfoCollectDO>().orderBy("submit_date");
		if(infoCollectDTO.getInfoStoreId()!=null) {
			wrapper.eq("info_store_id",infoCollectDTO.getInfoStoreId());
		}
		if(infoCollectDTO.getStatus()!=null){
			wrapper.eq("status",infoCollectDTO.getStatus());
		}
		// 查询列表数据
		Page<InfoCollectDO> page = infoCollectService.selectPage(getPage(InfoCollectDO.class),wrapper);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
				InfoCollectDO obj = (InfoCollectDO) page.getRecords().get(i);
				obj.setUserName(userService.selectById(obj.getUserId()).getName());
				if(obj.getCheckerId()!=null) {
					obj.setCheckerName(userService.selectById(obj.getCheckerId()).getName());
				}
				if(infoCollectDTO.getUserName()!=null){
					if(!obj.getUserName().contains(infoCollectDTO.getUserName()))
						continue;
				}
			list.add(obj);
		}
		page.setRecords(list);
        return Result.ok(page);
	}
	
	@GetMapping("/add")
	@RequiresPermissions("jzweb:infoCollect:add")
	String add(){
	    return "jzweb/infoCollect/add";
	}

	@GetMapping("/detail/{id}")
	@RequiresPermissions("jzweb:infoCollect:infoCollect")
	String edit(@PathVariable("id") Long id,Model model){
		model.addAttribute("infoCollectId",id);
	    return "jzweb/infoCollect/detail";
	}

	@PostMapping("/detailInfo")
	@ResponseBody
	@RequiresPermissions("jzweb:infoCollect:infoCollect")
	ApiResult<?> detailInfo(Long id){
		InfoCollectDO infoCollect = infoCollectService.selectById(id);
		Wrapper<InfoModelDO> infoModelDOWrapper = new EntityWrapper<InfoModelDO>().orderBy("sort");
		infoModelDOWrapper.eq("info_store_id",infoCollect.getInfoStoreId());
		List<InfoModelDO> infoModelDOList = infoModelService.selectList(infoModelDOWrapper);
		Map map = new HashMap();
		map.put("infoModelList",infoModelDOList);
		map.put("infoCollect",infoCollect);
		return ApiResult.success(map);
	}

	@GetMapping("/exportList")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:infoCollect:exportList")
	public void exportlist(HttpServletRequest request, HttpServletResponse response, String infoStoreId) throws Exception{

		if(infoStoreId==null || infoStoreId=="")
			return ;
		InfoStoreDO infoStoreDO = infoStoreService.selectById(infoStoreId);
		List<InfoModelDO> infoModelDOList = infoModelService.findByKv("info_store_id",infoStoreId);
		List<InfoCollectDO> infoCollectDOList = infoCollectService.findByKv("info_store_id",infoStoreId,"status",1);
		if(infoCollectDOList.size()<=0)
			return;
		List<String> headList = new ArrayList<String>();
		List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
		int modelLen = 0;
		for(InfoModelDO infoModelDO : infoModelDOList){
			if(infoModelDO.getType()==0||infoModelDO.getType()==5)continue;
			headList.add(infoModelDO.getName());
		}
		for(InfoCollectDO info : infoCollectDOList){

			Map<String,Object> map=JSONUtils.jsonToMap(info.getContent());
			mapList.add(map);
		}
		HSSFWorkbook workbook=EasyPoiUtil.createWorkBook(headList,mapList, infoStoreDO.getName());
		EasyPoiUtil.downLoadExcel(infoStoreDO.getName()+".xls",response,request,workbook);




		//List<Map<String,String>> list = new ArrayList<Map<String,String>>();
//		List<ExcelExportEntity> entityList = new ArrayList<ExcelExportEntity>();
//		List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
//		int modelLen = 0;
//		for(InfoCollectDO info : infoCollectDOList){
//			//map.addStaticAttribute("用户名",userService.selectById(info.getUserId()));
//			Map<String,Object> map=JSONUtils.jsonToMap(info.getContent());
//			for(String key :map.keySet()){
//				if(EfficacyUtil.isPhoto(map.get(key).toString())){
//					byte[] img = HttpClientUtil.getImageFromNetByUrl(map.get(key).toString());
//					map.put(key,img);
//				}
//			}
//			mapList.add(map);
//		}
//		for(int i=0;i<infoModelDOList.size();i++){
//			InfoModelDO model = infoModelDOList.get(i);
//			if(model.getType()==0||model.getType()==5)continue;
//			ExcelExportEntity entity = new ExcelExportEntity(model.getName(),model.getName());
//			double titleLen = model.getName().toString().length()*2.5;
//			//double contLen = mapList.get(0).get(model.getName()).toString().length()*1.5;
//			//if(titleLen>contLen)
//				entity.setWidth(titleLen);
//			//else entity.setWidth(contLen);
//			entityList.add(entity);
//			modelLen+=1;
//		}
//		ExportParams params = new ExportParams(infoStoreDO.getName(),infoStoreDO.getName(), ExcelType.XSSF);
//		params.setFreezeCol(modelLen);
//		ModelMap modelMap = new ModelMap();
//		modelMap.put(MapExcelConstants.MAP_LIST,mapList);
//		modelMap.put(MapExcelConstants.ENTITY_LIST,entityList);
//
//		modelMap.put(MapExcelConstants.PARAMS,params);
//		modelMap.put(MapExcelConstants.FILE_NAME,infoStoreDO.getName());
//		PoiBaseView.render(modelMap,request,response,MapExcelConstants.EASYPOI_MAP_EXCEL_VIEW);



	}

	
	@Log("添加")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:infoCollect:add")
	public Result<String> save( InfoCollectDO infoCollect){
		infoCollectService.insert(infoCollect);
        return Result.ok();
	}
	
	@Log("修改")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:infoCollect:edit")
	public Result<String>  update( InfoCollectDO infoCollect){
		boolean update = infoCollectService.updateById(infoCollect);
		return update ? Result.ok() : Result.fail();
	}
	
	@Log("删除")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:infoCollect:remove")
	public Result<String>  remove( Long id){
		infoCollectService.deleteById(id);
        return Result.ok();
	}
	
	@Log("批量删除")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:infoCollect:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		infoCollectService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}

	/**
	 * 表单审核
	 * @param ids
	 * @return
	 */
	@Log("审核")
	@PostMapping( "/review")
	@ResponseBody
	@RequiresPermissions("jzweb:infoCollect:review")
	public Result<String>  review(@RequestParam("ids[]") Long[] ids) {
			int i = 0;
			for (Long id : ids) {
				//查询这条数据ID
				InfoCollectDO infoCollectDO= infoCollectService.selectById(id);
				infoCollectDO.setStatus(0);
				boolean b = infoCollectService.updateById(infoCollectDO);
				if(b){
					i++;
				}
			}

			if (i == ids.length) {
				return Result.build(0,"已退回：" + i + "条数据");
			} else {
				return Result.fail("退回失败！");
			}

	}
	
}
